//
//  AppDelegate.m
//  ChengHuiTong
//
//  Created by KiVen on 15/11/2.
//  Copyright © 2015年 张文权. All rights reserved.
//
#import "AppDelegate.h"
#import "CoreLockConst.h"
#import "CLLockVC.h"
#import "CoreArchive.h"

#import "UMessage.h"

#import <UMengAnalytics-NO-IDFA/MobClick.h>
#import "YPStationMessageViewController.h"
#import "YPMessageDetailViewController.h"
#import "YPGuidanceViewController.h"
#import "AppDelegate+Add_Update.h"


#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

#define _IPHONE80_ 80000

#define iOSVersion ([[UIDevice currentDevice].systemVersion doubleValue])

@interface AppDelegate (){
    
    NSString*_hostUrl;

}

//当前屏幕与设计尺寸(iPhone6)宽度比例
@property (nonatomic, assign)CGFloat autoSizeScaleW;

//当前屏幕与设计尺寸(iPhone6)高度比例
@property (nonatomic, assign)CGFloat autoSizeScaleH;


@end

@implementation AppDelegate{
    
    NSString*downURL;
    
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];

    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    //实力导航栏去黑线
    [[UINavigationBar appearance]setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    

    [[UINavigationBar appearance]setShadowImage:[[UIImage alloc] init]];
    
    [[UINavigationBar appearance]setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];

    application.applicationIconBadgeNumber=0;
    

    [self saveUserName];
    
//    判断手势密码
   
//    友盟统计
    [self configurationUmengAnalytics];

    //友盟推送
    [self requestSystemPermissionsWithDic:launchOptions];
    
    [self.window makeKeyAndVisible];
    
    self.window.rootViewController=[[UIViewController alloc ]init];

    [self firstStartGuidance];

    return YES;
}



-(void)startRequest{
    
    
    [RequestModel getBaseUrlSuccessBlock:^(id obj) {
        if ([obj[@"status"] intValue]==0) {
            
            
            NSDictionary*dic=obj[@"data"];
            
            NSString*api_url=dic[@"api_url"];
            
            _hostUrl=api_url;
            
            NSLog(@"%@",api_url);
            
            
            YPShareAccountInfo*share=[YPShareAccountInfo shareAccountInfo];
            
            share.hostUrl=api_url;
            
            [share saveData];
            
            [self firstStartGuidance];
            
        }
        
        
    } failBlock:^(id obj) {
        
        
        //        [MBProgressHUD showError:@"网络链接失败" toView:self.view];
        
           [self firstStartGuidance];
        
        
    }];
    
    
}




//判断程序是不是第一次运行
- (void)firstStartGuidance{
    
 
     NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:version])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:version];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[YPShareAccountInfo shareAccountInfo] clearData];
        
        if ([CLLockVC hasPwd]) {
            
           [CoreArchive removeStrForKey:CoreLockPWDKey];
            
        }
        
        YPGuidanceViewController * guidanceVC = [[YPGuidanceViewController alloc]init];
        self.window.rootViewController = guidanceVC;
    }
    else
    {
        self.mainTabbar = [[MainTabbarViewController alloc]init];
        self.window.rootViewController = self.mainTabbar;
        //启动初始化接口
        [self requestAdvertisementAndUpdate];
        
    }
}

- (void)saveUserName{
    
    [LGToolMethods getUserDefaultsObjForKey:@"on"];
    
}

- (void)judgeGesture{
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    BOOL ison =  [defaults doubleForKey:@"hasPwd"];
    
    
    MainTabbarViewController * mainTabbar =(MainTabbarViewController *) self.window.rootViewController;
    if(!ison){
        
        NSLog(@"你还没有设置密码，请先设置密码");

        
    }else {
        
        [CLLockVC showModifyLockVCInVC:mainTabbar.recommendVC successBlock:^(CLLockVC *lockVC, NSString *pwd) {
            
          //  [lockVC dismiss:1.0f];

        }];
        
        [CLLockVC showVerifyLockVCInVC:mainTabbar.recommendVC  ishome:NO  forgetPwdBlock:^{
            
            NSLog(@"忘记密码");
            
        } successBlock:^(CLLockVC *lockVC, NSString *pwd) {
            
            NSLog(@"密码正确");
            
            [lockVC dismiss:1.0f];
            
        }];
        
        
        
    }

}
/**
 *  配置友盟统计SDK
 */
-(void)configurationUmengAnalytics{
    
    /*
     注册app
     */
    [MobClick startWithAppkey:kUmeng_Analytics_Key reportPolicy:REALTIME   channelId:nil];
    /*
     以App打包时的Build号作为应用程序的版本标识，不能通过友盟SDK或友盟后台配置。
     友盟SDK为了兼容Xcode3的工程，默认取的是Build号，如果需要取Xcode4及以上版本的Version，可以使用下面的方法；
     */
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    
    /** 设置是否对日志信息进行加密, 默认NO(不加密). */
    [MobClick setEncryptEnabled:YES];
    
    /** 设置是否开启background模式, 默认YES. */
    [MobClick setBackgroundTaskEnabled:YES];
    /*
     友盟iOS统计SDK默认自带错误分析功能，不需要开发者手动调用。
     如果开发者自己做了错误捕捉，可以调用下面方法关闭友盟的错误统计
     */
    [MobClick setCrashReportEnabled:YES];
    
}

#pragma mark - ScaleSize
- (CGFloat)autoSizeScaleH{
    if (_autoSizeScaleH == 0) {
        if (SCREEN_WIDTH > 414) {
            _autoSizeScaleH = 1;
            
        }else{
            _autoSizeScaleH = SCREEN_HEIGHT / 667;
        }
    }
    return _autoSizeScaleH;
}

- (CGFloat)autoSizeScaleW{
    if (_autoSizeScaleW == 0) {
        if (SCREEN_WIDTH > 414) {
            _autoSizeScaleW = 1;
            
        }else{
            _autoSizeScaleW = SCREEN_WIDTH / 375;
            
        }
    }
    return _autoSizeScaleW ;
}

- (CGFloat)autoScaleW:(CGFloat)w{
    
    return w * self.autoSizeScaleW;
    
}

- (CGFloat)autoScaleH:(CGFloat)h{
    
    return h * self.autoSizeScaleH;
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
     application.applicationIconBadgeNumber=0;
    
}

-(void)requestSystemPermissionsWithDic:(NSDictionary *)launchOptions{
    
    //    配置通知
    [UMessage startWithAppkey:@"56e7820567e58e8117000f6d" launchOptions:launchOptions];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"接受";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"拒绝";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    
    //register remoteNotification types
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
    
#endif

    //从通知进来调用didReceive方法
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSDictionary *pushDict = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    NSLog(@"%@",pushDict);
    if (pushDict) {
        [[UIApplication sharedApplication].delegate application:[UIApplication sharedApplication] didReceiveRemoteNotification:pushDict];
    }
    
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    NSString *deviceKey = deviceToken.description;
    if (deviceKey) {
        deviceKey = [deviceKey stringByReplacingOccurrencesOfString:@"<" withString:@""];
        deviceKey = [deviceKey stringByReplacingOccurrencesOfString:@">" withString:@""];
        deviceKey = [deviceKey stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    }
    
    [UMessage registerDeviceToken:deviceToken];
    
    [LGToolMethods saveUserDefaultsObj:deviceKey forKey:@"deviceKey"];
    NSLog(@"获取令牌成功:%@",deviceKey);

}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0){
    
    
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    NSLog(@"userInfo:%@",userInfo);
    
    [UMessage setAutoAlert:NO];

    MainTabbarViewController * mainTabbar =(MainTabbarViewController *) self.window.rootViewController;
    
    mainTabbar.assetsVC.readView.hidden=NO;

    NSLog(@"%ld",(long)application.applicationState);
    
    if (application.applicationState==UIApplicationStateInactive){
        
         application.applicationIconBadgeNumber=0;
        
        YPStationMessageViewController * stationMessageVC = [[YPStationMessageViewController alloc]init];
                
        [mainTabbar.viewControllers[mainTabbar.selectedIndex] pushViewController:stationMessageVC animated:YES ];
        
    }

    
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
